﻿using System.Services;
using System.Threading.Tasks;
using Windows.Devices.Sensors;

namespace System.Sensors
{
    public interface ILightSensorService : ISensorService<LightSensor, LightSensorReading>
    {
    }

    [ExportService("LightSensorService", "", typeof(ILightSensorService), int.MaxValue)]
    public class LightSensorService : SensorServiceBase<LightSensor, LightSensorReading>, ILightSensorService
    {
        public LightSensorService()
        {
        }

        public override void StartService()
        {
            Sensor = LightSensor.GetDefault();
            base.StartService();
        }

        public override void Subscribe()
        {
            if (IsSensorAvailable)
                Sensor.ReadingChanged += Sensor_ReadingChanged;

            base.Subscribe();
        }

        public override void Unsubscribe()
        {
            if (IsSensorAvailable)
                Sensor.ReadingChanged -= Sensor_ReadingChanged;

            base.Unsubscribe();
        }

        void Sensor_ReadingChanged(LightSensor sender, LightSensorReadingChangedEventArgs args)
        {
            if (EventAggregator != null)
                EventAggregator.Publish<LightSensorServiceReadingMessage>(new LightSensorServiceReadingMessage(this, args.Reading));
        }

        protected override async Task<LightSensorReading> GetSensorData()
        {
            return Sensor.GetCurrentReading();
        }

        public override uint GetMinimumReportInterval()
        {
            return Sensor.MinimumReportInterval;
        }

        public override uint GetReportInterval()
        {
            return Sensor.ReportInterval;
        }

        public override void SetReportInterval(uint value)
        {
            Sensor.ReportInterval = value;
        }
    }

    public class LightSensorServiceReadingMessage : SensorReadingMessageBase<LightSensorReading>
    {
        public LightSensorServiceReadingMessage(object sender, LightSensorReading value)
            : base(sender, value)
        {
        }
    }
}
